//
//  CollectionViewController.m
//  Linkage
//
//  Created by LeeJay on 16/8/22.
//  Copyright © 2016年 LeeJay. All rights reserved.
//
#import "CollectionViewController.h"
#import "CollectionViewHeaderView.h"
#import "LJCollectionViewFlowLayout.h"

#import "LeftTableViewCell.h"
#import "LeftTableViewModel.h"

#import "CollectionCategoryModel.h"
#import "CollectionViewCell.h"
#import "WHRCropHomeVC.h"


@interface CollectionViewController () <UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate,UICollectionViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *collectionDatas;

@end

@implementation CollectionViewController
{
    NSInteger _selectIndex;
    BOOL _isScrollDown;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _selectIndex = 0;
    _isScrollDown = YES;

    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.collectionView];
    [self requestStairList];
    
    
    [self setupNavigationItems];
}

//自定义UIBarButtonItem
- (void)setupNavigationItems {
    
    /** 导航条左边的按钮 */
    //返回按钮
    UIButton *kfBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [kfBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    kfBtn.frame = CGRectMake(0, 0, 60, 30);
    [kfBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:kfBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
  
    /** 搜索 */
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
    titleLabel.text = @"作物分类";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = FONT_EIGHTEEN;
    titleLabel.textColor = [UIColor colorWithHex:0x29b566];
    self.navigationItem.titleView = titleLabel;
    
    
}

#pragma mark - Action

- (void)backAction:(UIBarButtonItem *)item {
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Getters

- (NSMutableArray *)dataSource
{
    if (!_dataSource)
    {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (NSMutableArray *)collectionDatas
{
    if (!_collectionDatas)
    {
        _collectionDatas = [NSMutableArray array];
    }
    return _collectionDatas;
}

- (UITableView *)tableView
{
    if (!_tableView)
    {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 80, SCREEN_HEIGHT)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.rowHeight = 44;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorColor = [UIColor clearColor];
        [_tableView registerClass:[LeftTableViewCell class] forCellReuseIdentifier:kCellIdentifier_Left];
    }
    return _tableView;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        LJCollectionViewFlowLayout *flowlayout = [[LJCollectionViewFlowLayout alloc] init];
        //设置滚动方向
        [flowlayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        //左右间距
        flowlayout.minimumInteritemSpacing = 2;
        //上下间距
        flowlayout.minimumLineSpacing = 2;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(2 + 80, 2 + 64, SCREEN_WIDTH - 80 - 4, SCREEN_HEIGHT - 64 - 4) collectionViewLayout:flowlayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView setBackgroundColor:[UIColor whiteColor]];
        //注册cell
        [_collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:kCellIdentifier_CollectionView];
        //注册分区头标题
        [_collectionView registerClass:[CollectionViewHeaderView class]
            forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                   withReuseIdentifier:@"CollectionViewHeaderView"];
        _collectionView.bounces = YES;
        _collectionView.alwaysBounceVertical = YES;
    }
    return _collectionView;
}

#pragma mark - UITableView DataSource Delegate



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Left forIndexPath:indexPath];
    LeftTableViewModel *model = self.dataSource[indexPath.row];
    cell.name.text = model.classificationName;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    _selectIndex = indexPath.row;
    /** 调用二级接口 */
    LeftTableViewModel *model = self.dataSource[indexPath.row];
    [self getCollectionData:model.classificationId];
   
}

#pragma mark - UICollectionView DataSource Delegate

/** collectionView的点击方法  */

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CollectionCategoryModel *model = self.collectionDatas[indexPath.row];
    WHRCropHomeVC *vc = [[WHRCropHomeVC alloc]init];
    /** 给下一个界面传值 */
    vc.cropId = model.cropId;
    vc.cropImg = model.cropImg;
    
    [self.navigationController pushViewController:vc animated:YES];
    
    
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _collectionDatas.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellIdentifier_CollectionView forIndexPath:indexPath];
    CollectionCategoryModel *model = self.collectionDatas[indexPath.row];
    cell.model = model;
    if (_collectionView.contentSize.height < _collectionView.frame.size.height) {
        _collectionView.contentSize = CGSizeMake(0, _collectionView.frame.size.height);
    }
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((SCREEN_WIDTH - 80 - 4 - 4) / 3,
                      (SCREEN_WIDTH - 80 - 4 - 4) / 3 + 30);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    NSString *reuseIdentifier;
    if ([kind isEqualToString:UICollectionElementKindSectionHeader])
    { // header
        reuseIdentifier = @"CollectionViewHeaderView";
    }
    CollectionViewHeaderView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                        withReuseIdentifier:reuseIdentifier
                                                                               forIndexPath:indexPath];
    if ([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        if (self.dataSource.count > 0) {
            
            LeftTableViewModel *model = self.dataSource[_selectIndex];
            view.title.text = model.classificationName;
        }
       
    }
    return view;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(SCREEN_WIDTH, 30);
}




#pragma mark - requestNetwork
/** 网络请求一级 */
- (void)requestStairList{
    
    ZX_WEAK_SELF
    
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    
    [NetWorkHelp yl_postDataWith:params url:URL_SPLIT(URL_AgricultureCircle,  URL_AgricultureCircle_queryCftLevelOneList) success:^(id respose) {
        
        
        if ([respose[@"header"][@"statusCode"] integerValue] == 200) {
            
            weakSelf.dataSource = [LeftTableViewModel mj_objectArrayWithKeyValuesArray:respose[@"body"][@"queryAllCropCftList"]];
            
               [self.tableView reloadData];
            
            if (self.dataSource.count > 0) {

                 [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
            }

            
            
        } else if ([respose[@"header"][@"statusCode"] integerValue] != 200) {
            
        }
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
       
        LeftTableViewModel *model = self.dataSource[0];
        [self getCollectionData:model.classificationId];
        
    } failure:^(NSError *error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    }];
    

    
}



- (void)getCollectionData:(NSString *)index {
    
   
    ZX_WEAK_SELF
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
   
    params[@"classificationId"] =index;
    [NetWorkHelp yl_postDataWith:params url:URL_SPLIT(URL_AgricultureCircle, URL_AgricultureCircle_findCropByCftId) success:^(id respose) {
        
        
        if ([respose[@"header"][@"statusCode"] integerValue] == 200) {
            
            weakSelf.collectionDatas = [CollectionCategoryModel mj_objectArrayWithKeyValuesArray:respose[@"body"][@"cropList"]];
            
         
            
        } else if ([respose[@"header"][@"statusCode"] integerValue] != 200) {
            
        }
        
        [self.collectionView reloadData];
        
    } failure:^(NSError *error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
        
    }];
}


@end
